package com.example.safeassistan.my.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.my.adapter.CheckRecordTypeAdapter;
import com.example.safeassistan.my.adapter.HistoryTaskListAdapter;
import com.example.safeassistan.my.model.CheckRecordTypeModel;
import com.example.safeassistan.my.model.HistoryTaskListModel;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.MyLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class HistoryTaskList  extends BaseActivity implements View.OnClickListener {

    private HistoryTaskListAdapter adapter;
    private List<HistoryTaskListModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcView;
    private TextView tvRightBar;
    private RelativeLayout rlTopBar;
    private LinearLayout llNodata;
    private SmartRefreshLayout refresh;
    private CheckRecordTypeModel model;
    private ImageView ivBack;
    private int currentPage=1;
    private String checkTypeId="";
    private String dateTime="";
    private int count=0;
    private int defStatus=-1;
    PopupWindow popupWindow;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, HistoryTaskList.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvRightBar:
                //筛选
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.top_popuwindow_screen,null);
                popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                LinearLayout llChiose=inflate.findViewById(R.id.llChiose);
                TextView tvSure=inflate.findViewById(R.id.tvSure);
                TextView tvReset=inflate.findViewById(R.id.tvReset);
                TextView tvChecked=inflate.findViewById(R.id.tvChecked);
                TextView tvOverDue=inflate.findViewById(R.id.tvOverDue);
                TextView tvCheckTime=inflate.findViewById(R.id.tvCheckTime);

                RecyclerView mFlowViewGroup=inflate.findViewById(R.id.mFlowViewGroup);
                MyLayoutManager myLayoutManager=new MyLayoutManager(this,true);
                CheckRecordTypeAdapter typeAdapter=new CheckRecordTypeAdapter(model.getResult());
                mFlowViewGroup.setLayoutManager(myLayoutManager);
                mFlowViewGroup.setAdapter(typeAdapter);
                typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                     @Override
                     public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                         for (int i=0;i<model.getResult().size();i++){
                             model.getResult().get(i).setSelecte(false);
                         }
                         checkTypeId=model.getResult().get(position).getId();
                         model.getResult().get(position).setSelecte(true);
                         typeAdapter.notifyDataSetChanged();
                     }
                });

                tvChecked.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        defStatus=2;
                        tvChecked.setBackgroundResource(R.drawable.stoke_blue_bg);
                        tvChecked.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                        tvOverDue.setBackgroundResource(R.drawable.stoke_gray_bg);
                        tvOverDue.setTextColor(getResources().getColor(R.color.gray9));
                    }
                });

                tvOverDue.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        defStatus=3;
                        tvChecked.setBackgroundResource(R.drawable.stoke_gray_bg);
                        tvChecked.setTextColor(getResources().getColor(R.color.gray9));
                        tvOverDue.setBackgroundResource(R.drawable.stoke_blue_bg);
                        tvOverDue.setTextColor(getResources().getColor(R.color.blue_3B5BEA));
                    }
                });

                llChiose.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerView endTime = new TimePickerBuilder(HistoryTaskList.this, new OnTimeSelectListener() {
                            @Override
                            public void onTimeSelect(Date date, View v) {//选中事件回调
                                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                                tvCheckTime.setText(simpleDateFormat.format(date));
                                dateTime=simpleDateFormat.format(date);
                            }
                        })
                                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                                .setCancelText("取消")//取消按钮文字
                                .isDialog(true)
                                .setSubmitText("确定")//确认按钮文字
                                .setTitleSize(18)//标题文字大小
                                .setTitleColor(getResources().getColor(R.color.white))
                                .setTitleText("检查日期")
                                .setContentTextSize(17)
                                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                                .isCyclic(true)//是否循环滚动
                                .setTextColorOut(getResources().getColor(R.color.gray6))
                                .setTextColorCenter(getResources().getColor(R.color.blue_3B5BEA))
                                .setSubmitColor(getResources().getColor(R.color.white))//确定按钮文字颜色
                                .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                                .isCenterLabel(false) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                                .build();
                        endTime.show();
                    }
                });

                tvSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvReset.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dateTime="";
                        checkTypeId="";
                        defStatus=-1;
                        popupWindow.dismiss();
                    }
                });

                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(rlTopBar,0,0);
                break;
            case R.id.ivBack:
                finish();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.history_task_list;
    }

    @Override
    protected void initView() {
        rcView=findViewById(R.id.rcView);
        tvRightBar=findViewById(R.id.tvRightBar);
        rlTopBar=findViewById(R.id.rlTopBar);
        refresh=findViewById(R.id.refresh);
        llNodata=findViewById(R.id.llNodata);
        ivBack=findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this::onClick);
        tvRightBar.setOnClickListener(this::onClick);
        setView();
        getData();
        getType();
    }

    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            if (dateTime!=null&&!dateTime.equals("")){
                map.put("dateTime",dateTime);
            }
            if (checkTypeId!=null&&!checkTypeId.equals("")){
                map.put("checkTypeId",checkTypeId);
            }
            if (defStatus!=-1){
                map.put("defStatus",defStatus);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(HistoryTaskList.this).doPost(UrlConstants.getMyHistoryList, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), HistoryTaskListModel.class);
                        if (obj instanceof HistoryTaskListModel) {
                            HistoryTaskListModel model=(HistoryTaskListModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    adapter=new HistoryTaskListAdapter(data);
                                    rcView.setLayoutManager(new LinearLayoutManager(HistoryTaskList.this));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            HistoryTaskCheckLogActivity.actionStart(getContext(),data.get(position).getId());
                                        }
                                    });
                                } else {
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(HistoryTaskList.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }

    //获取历史任务类型
    public void getType(){
        new HttpRequest(this).doPost(UrlConstants.getAllCheckType, null, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), CheckRecordTypeModel.class);
                        if (obj instanceof CheckRecordTypeModel) {
                            model=(CheckRecordTypeModel) obj;
                        }
                    }else {
                        Toast.makeText(HistoryTaskList.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }
}